/**
 * 
 */
package com.itinsys.enma.service.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

import com.itinsys.enma.util.InternalMessageService;

/**
 * @author Pablo
 *
 */
public class EnmaAuthFailureHandler extends	SimpleUrlAuthenticationFailureHandler {

	private String defaultFailureUrl;
	@Autowired
	private InternalMessageService messageService;
	
	public EnmaAuthFailureHandler(String defaultFailureUrl) {
		setDefaultFailureUrl(defaultFailureUrl);
	}

	
	
	public EnmaAuthFailureHandler() {
		super();
		// TODO Auto-generated constructor stub
	}



	public void setDefaultFailureUrl(String defaultFailureUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl),
                "'" + defaultFailureUrl + "' is not a valid redirect URL");
        this.defaultFailureUrl = defaultFailureUrl+"";
    }
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        if (defaultFailureUrl == null) {
            logger.debug("No failure URL set, sending 401 Unauthorized error");

            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + messageService.getMessage(exception.getMessage()));
        } else {
            saveException(request, exception);

            if (isUseForward()) {
                logger.debug("Forwarding to " + defaultFailureUrl+exception.getMessage());

                request.getRequestDispatcher(defaultFailureUrl+exception.getMessage()).forward(request, response);
            } else {
                logger.debug("Redirecting to " + defaultFailureUrl+exception.getMessage());
                getRedirectStrategy().sendRedirect(request, response, defaultFailureUrl+exception.getMessage());
            }
        }
    }
}
